using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace ShareDev.Webparts.Gallery.UI.WebControls.WebParts
{
    [Guid("95939451-3C4E-4ee4-B2C7-467AD13E31F0")]
    [DefaultProperty("Text"),
        ToolboxData("<{0}:SmoothDivScrollWebPart runat=server></{0}:SmoothDivScrollWebPart>"),
        XmlRoot(Namespace = "ShareDev.Webparts.Gallery.UI.WebControls.WebParts")]
    public class SmoothDivScrollWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        #region Privates variables

        private bool _error = false;
        private string _listName = null;
        private string _cssStyle = null;
        private string _gallery = string.Empty;

        #endregion

        #region Custom properties

        #region ListName

        /// <summary>
        /// Property that represents the name of library list of images to the gallery.
        /// </summary>

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Miscellaneous")]
        [WebDisplayName("Name of the image library")]
        [WebDescription("Name of the image library that is displayed in the gallery")]
        public string ListName
        {
            get
            {
                if (_listName == null)
                    _listName = "";
                return _listName;
            }
            set { _listName = value; }
        }

        #endregion

        #region CSSStyle

        /// <summary>
        /// Property that represents the CSS code to the gallery
        /// </summary>

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Miscellaneous")]
        [WebDisplayName("CSS Style")]
        [WebDescription("CSS Style to gallery")]
        public string CSSStyle
        {
            get
            {
                if (_cssStyle == null)
                    _cssStyle = this.CSSContent();

                return _cssStyle;
            }
            set { _cssStyle = value; }
        }

        #endregion

        #endregion

        #region Webpart events

        public SmoothDivScrollWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {
                    base.CreateChildControls();
                    this.Controls.Add(new LiteralControl(this.ListName));
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.IncludeHeaders();
            
        }

        protected override void RenderWebPart(HtmlTextWriter output)
        {
            this.RenderingImages();
            output.Write(_gallery);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        #endregion

        #region Custom events

        #region Include headers

        private void IncludeHeaders()
        {
            HtmlLink _css = null;

            StringBuilder _script = null;
            LiteralControl _scriptJS = null;

            #region files

            _css = new HtmlLink();
            _css.Href = "_layouts/SmoothDivScroll/themes/SmoothDivScroll.css";
            _css.Attributes["rel"] = "stylesheet";
            _css.Attributes["type"] = "text/css";
            _css.Attributes["media"] = "all";
            this.Page.Header.Controls.Add(_css);

            _scriptJS = new LiteralControl();
            _scriptJS.Text = "<style type='text/css'>";
            _scriptJS.Text += this.CSSStyle;
            _scriptJS.Text += "></style>";

            _scriptJS.Text = "<script type='text/javascript' ";
            _scriptJS.Text += "src='catalogs/masterpage/_layouts/SmoothDivScroll/js/jquery-1.5.min.js'";
            _scriptJS.Text += "></script>";

            _scriptJS.Text += "<script type='text/javascript' ";
            _scriptJS.Text += "src='catalogs/masterpage/_layouts/SmoothDivScroll/js/SmoothDivScroll.1.0.1.js'";
            _scriptJS.Text += "></script>";

            this.Page.Header.Controls.Add(_scriptJS);

            #endregion

            #region scripts blocks

            _script = new StringBuilder();

            _script.Append("<script type='text/javascript'>");
            _script.Append("jQuery(function ($) {");
            _script.Append("$('.circle').SmoothDivScroll({opacity: 0.8});");
            _script.Append("$('.fade').SmoothDivScroll();");
            _script.Append("$('.bar').SmoothDivScroll({animation: 'slide'});");
            _script.Append("$('.bar2').SmoothDivScroll({animation: 'slide'});");
            _script.Append("$('.bar3').SmoothDivScroll({animation: 'slide', anchor_y: 'top'});");
            _script.Append("$('.cover').SmoothDivScroll({animation: 'slide', hover_x: '400px'});");
            _script.Append("$('.cover2').SmoothDivScroll({animation: 'slide', anchor_y: 'top', hover_y: '80px' });");
            _script.Append("$('.cover3').SmoothDivScroll({animation: 'slide', hover_x: '400px', hover_y: '300px'});");
            _script.Append("});");
            _script.Append("</script>");

            _scriptJS = new LiteralControl();
            _scriptJS.Text = _script.ToString();
            this.Page.Header.Controls.Add(_scriptJS);

            #endregion
        }

        #endregion

        #region Rendering images in the gallery

        /// <summary>
        /// Reading library and mount HTML code to SmoothDivScroll gallery
        /// </summary>
        private void RenderingImages()
        {
            SPQuery _query = new SPQuery();
            string _effect = string.Empty;
            string _actionLink = string.Empty;

            if (this.ListName == string.Empty)
                return;

            try
            {
                using (SPWeb _web = SPContext.Current.Web)
                {
                    //Reading list with fields predefined the model
                    foreach (SPListItem _item in
                        _web.Lists[this.ListName].GetItems(_query))
                    {
                        if (_item.Fields["Effect"] != null)
                            _effect = this.EffectTrans(_item["Effect"].ToString());
                        else
                            _effect = this.EffectTrans("Fade");

                        _actionLink = Convert.ToString(_item["Action URL"]);
                        if (_actionLink != string.Empty)
                            _actionLink = _actionLink.Split(';').GetValue(0).ToString();

                        _gallery += string.Format("<div class=\"SmoothDivScroll-block {0}\">", _effect);
                        _gallery += string.Format("<a href=\"{0}\" target=\"_blank\" class=\"SmoothDivScroll-overlay\">", _item["Action URL"]);
                        _gallery += "<div class=\"details\">";
                        _gallery += string.Format("<h4>{0}</h4><br/>", _item["Title"]);
                        _gallery += string.Format("<p>{0}</p>", _item["Description"]);
                        _gallery += "</div>";
                        _gallery += "</a>";
                        _gallery += string.Format("<div class=\"SmoothDivScroll-backdrop\"><img src=\"{0}/{1}\"/></div>", 
                            SPContext.Current.Web.Url, _item.File.Url);
                        _gallery += "</div>";
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region Effects translation

        private string EffectTrans(string pEfeitos)
        {
            switch (pEfeitos)
            {
                case "Circle":
                    return "circle";
                    break;

                case "Fade":
                    return "fade";
                    break;

                case "Bar":
                    return "bar";
                    break;
                
                case "Bar 2":
                    return "bar2";
                    break;

                case "Bar 3":
                    return "bar3";
                    break;

                case "Cover":
                    return "cover";
                    break;

                case "Cover 2":
                    return "cover2";
                    break;

                case "Cover 3":
                    return "cover3";
                    break;

                default:
                    return "circle";
            }
        }

        #endregion

        #region CSS file reader

        private string CSSContent()
        {
            StringBuilder _cssContent = null;

            try
            {
                _cssContent = new StringBuilder();
                _cssContent.Append("#content {width: 845px !important; margin: 20px auto !important; padding: 10px 30px !important; }");
                _cssContent.Append(".clearfix {display: block !important; height: 0 !important; clear: both !important; visibility: hidden !important;}");
                _cssContent.Append(".details {margin: 15px 20px !important;}");
                _cssContent.Append("h4 {font: 300 16px 'Helvetica Neue' , Helvetica, Arial, sans-serif !important; line-height: 160% !important; letter-spacing: 0.15em !important; color: #fff !important; text-shadow: 1px 1px 0 rgb(0,0,0) !important;}");
                _cssContent.Append("p {font: 300 12px 'Lucida Grande' , Tahoma, Verdana, sans-serif !important; color: #aaa !important; text-shadow: 1px 1px 0 rgb(0,0,0) !important; }");
                _cssContent.Append("a {text-decoration: none !important;}");

                return _cssContent.ToString();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        #endregion

        #endregion
    }
}
